<?php

class UsersController extends FController
{
	public $layout='//layouts/main';   
	/* 
		Function init can not set default theme for this controller
		It must be set in earch action
	*/ 


	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionCreate()
	{
		$model=new FormUser;
		$profile=new Profile;
		
		if(!empty($_POST['FormUser']))
		{
			
			// dump(Yii::app()->getModule('user')->isAdmin());
			$model->attributes=$_POST['FormUser'];
			$model->activkey=UserModule::encrypting(microtime().$model->password);
			$model->createtime=time();
			$model->lastvisit=time();
			$model->superuser=0;
			$model->sex=$_POST['FormUser']['sex'];
			$model->country_id=$_POST['FormUser']['country_id'];
			
			
			$profile->firstname=$model->firstname;
			$profile->lastname=$model->lastname;
			$profile->user_id=0;
			
			
			if($model->validate()) {
				$model->password=UserModule::encrypting($model->password);
				
				$user = new User;
				$user->attributes = $model->attributes;
				$user->country_id = $model->country_id;
				$user->password = $model->password;
				$user->activkey = $model->activkey;
				$user->status = 1;
				
				if($user->save()) {
					
					$profile->user_id=$user->id;
					$profile->save();
					Rights::assign('User', $user->id);
					Yii::app()->user->setFlash('success', 'Account created successfully.');
				}else{
					
				}
				
				$this->redirect(array('/users/login'));
			} else{
				
				// $model->validate();
			}
		}
		
    	Yii::import('application.modules.countries.models.Country');
		$countries = Country::model()->findAll($criteria);
		$countries = CHtml::listData($countries, 'id', 'name');
		$this->render('create',array(
			'model'=>$model,
			'profile'=>$profile,
			'countries'=>$countries,
		));
	}
	
	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		
		if (Yii::app()->user->isGuest) {
			
			$model=new UserLogin;
			// collect user input data
			if(!empty($_POST['UserLogin']))
			{
				
				$model->attributes=$_POST['UserLogin'];
				// dump($model->attributes);
				// validate user input and redirect to previous page if valid
				if($model->validate()) {
					
					
					$this->redirect('/');
				}else{
					
				}
			}
			// display the login form
			$this->render('login',array('model'=>$model));
		} else{
			// if(Yii::app()->controller->module->returnUrl != null)
				// $this->redirect(Yii::app()->controller->module->returnUrl);
			// else
				$this->redirect(Yii::app()->createUrl('/articles'));
		}
	}
	
	public function actionConnectFB()
	{
		// dump($this->convertToLatin("Trương"));
		$user = Yii::app()->request->getParam('id');
		if(!empty($_POST)){
			$username = "";
			$first_name = "";
			$last_name = "";
			$email = "";
			$birth = "";
			
			$info = $_POST['info'];
			
			if(!empty($info['first_name'])) $first_name = $this->convertToLatin($info['first_name']);
			if(!empty($info['username'])) $username = $info['username'];
			if(!empty($info['last_name'])) $last_name = $this->convertToLatin($info['last_name']);
			if(!empty($info['email'])) $email = $info['email'];
			if(!empty($info['birthday'])) $birth = date("Y-m-d",strtotime($info['birthday']));
			
			$userEmail = User::model()->findByAttributes(array('email'=>$email));
			$userFacebook = UserFacebook::model()->findByAttributes(array('fb_id'=>$user));
			
			
			
			
			if(!empty($userEmail) && !empty($userFacebook)){
				
				$profile = Profile::model()->findByAttributes(array(
					'user_id'=>$userEmail->id
				));
				if(empty($profile)){
					$profile=new Profile;
					$profile->firstname=$first_name;
					$profile->lastname=$last_name;
					$profile->user_id=$userEmail->id;
					$profile->save();
				}
				
				$user = UserFacebook::forceLogin($userEmail->id);
				jsonOut(array(
					'error'=>false,
					'message'=>'Get info sucessfully.',
					'post'=>false,
					'data'=>$userEmail->attributes,
				));
			}else{
				if(empty($userEmail)){
					UserFacebook::model()->deleteAllByAttributes(array('fb_id'=>$user));
					
					$model = new User;
					$model->email = $email;
					$model->username = strtolower($first_name.$last_name);
					$model->lastname = $last_name;
					$model->firstname = $first_name;
					$model->birthday = $birth;
					$model->createtime = time();
					
					
					
					
					$model->password = UserModule::encrypting(uniqid(32));

					if($model->save()){
					
						$profile = Profile::model()->findByAttributes(array(
							'user_id'=>$model->id
						));
						if(empty($profile)){
							$profile=new Profile;
							$profile->firstname=$first_name;
							$profile->lastname=$last_name;
							$profile->user_id=$model->id;
							$profile->save();
						}
						
						$modelFB = new UserFacebook;
						$modelFB->user_id = $model->id;
						$modelFB->fb_id = $user;
						$modelFB->fb_email = $email;
						
						Rights::assign('User', $model->id);
						if(!$modelFB->save()){
							$errors  = $modelFB->getErrors();
							list ($field, $_errors) = each ($errors);
							jsonOut(array(
								'error'=>true,
								'message'=>'Save facebook mapped failer. '.$_errors[0],
							));
						}else{
							
							
								
								$user = UserFacebook::forceLogin($model->id);
								
								
								
								jsonOut(array(
									'error'=>false,
									'message'=>'Get info sucessfully.',
									'post'=>true,
									'data'=>$model->attributes,
									
								));
							
							
						}
					}else{
						$errors  = $model->getErrors();
						list ($field, $_errors) = each ($errors);
						jsonOut(array(
							'error'=>true,
							'message'=>'Save facebook mapped failer. '.$_errors[0] . @CJSON::encode($model->attributes),
						));
					}
				}else{
					UserFacebook::model()->deleteAllByAttributes(array('fb_id'=>$user));
					$modelFB = new UserFacebook;
					$modelFB->user_id = $userEmail->id;
					$modelFB->fb_id = $user;
					$modelFB->fb_email = $email;
					if(!$modelFB->save()){
						$errors  = $modelFB->getErrors();
						list ($field, $_errors) = each ($errors);
						jsonOut(array(
							'error'=>true,
							'message'=>'Save facebook mapped failer. '.$_errors[0],
						));
					}else{
						$userEmail->id = $userEmail->id;
						jsonOut(array(
							'error'=>false,
							'message'=>'Get info sucessfully.',
							'data'=>$userEmail->attributes,
							'post'=>$_POST
						));
					}
				}
			}
			
		}else{
			jsonOut(array(
				'error'=>true,
				'message'=>'Request invalid.'
			));
		}
	}
	public static function convertToLatin($str) {
		if(!$str) return false;
		$unicode = array(
		  'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
		  'd'=>'đ',
		  'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
		  'i'=>'í|ì|ỉ|ĩ|ị',
		  'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
		  'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
		  'y'=>'ý|ỳ|ỷ|ỹ|ỵ',
		);
		foreach($unicode as $nonUnicode=>$uni) $str = preg_replace("/($uni)/i",$nonUnicode,$str);
		return $str;
	}
	
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect("/");
	}
	
	public function actionCategoryAuthor() {
		if(currentUser() == false){
			$this->redirect(array('/users/login'));
		}
		$dataProvider = new CActiveDataProvider('UserCategory',array(
			'criteria'=>array(
				'condition'=>'user_id='.Yii::app()->user->id,
				'order'=>'created DESC',
			),
		));
		$this->render('categoryAuthor', array(
			'dataProvider' => $dataProvider,
		));
	}
	public function actionAddCategory() {
		if(currentUser() == false){
			$this->redirect(array('/users/login'));
		}
		$allUserCategory = UserCategory::model()->findAll(array('condition'=>'user_id == '.Yii::app()->user->id,));
		if(count($allUserCategory) < 3) {
			$model = new UserCategory;
			if (isset($_POST['UserCategory'])) {
				$model->setAttributes($_POST['UserCategory']);
				$model->user_id = Yii::app()->user->id;
				if ($model->save()) {
					if (Yii::app()->getRequest()->getIsAjaxRequest())
						Yii::app()->end();
					else
						$this->redirect(array('categoryAuthor', 'id' => $model->id));
				}
			}
			$this->render('addCategory', array( 'model' => $model));
		} else {
			Yii::app()->user->setFlash('error', 'You have maximum categories.');
			$this->redirect(array('categoryAuthor', 'id' => $model->id));
		}
	}
	public function actionUpdateCategory($id) {
		if(currentUser() == false){
			$this->redirect(array('/users/login'));
		}
		$model = UserCategory::model()->findbyPk($id);
		if (isset($_POST['UserCategory'])) {
			$model->setAttributes($_POST['UserCategory']);
			$model->user_id = Yii::app()->user->id;
			if ($model->save()) {
				if (Yii::app()->getRequest()->getIsAjaxRequest())
					Yii::app()->end();
				else
					$this->redirect(array('categoryAuthor', 'id' => $model->id));
			}
		}
		$this->render('addCategory', array( 'model' => $model));
	}
	public function actionCreateCategory() {
		$allUserCategory = UserCategory::model()->findAll(array('condition'=>'user_id == '.Yii::app()->user->id,));
		if(count($allUserCategory) < 3) {
			$model = new Category;
			if (isset($_POST['Category'])) {
				$model->setAttributes($_POST['Category']);
				//$model->attributes=$_POST['Category'];
				$model->name = $_POST['Category']['name'];
				$model->user_id = Yii::app()->user->id;
				$model->country_id = Country::model()->visitorCountryID();
				if ($model->save()) {
					$userCategoryModel = new UserCategory;
					$userCategoryModel->user_id = Yii::app()->user->id;
					$userCategoryModel->category_id = $model->id;
					$userCategoryModel->save();
					if (Yii::app()->getRequest()->getIsAjaxRequest())
						Yii::app()->end();
					else
						$this->redirect(array('categoryAuthor', 'id' => $model->id));
				}
			}
			$this->render('createCategory', array( 'model' => $model));
		} else {
			Yii::app()->user->setFlash('error', 'You have maximum categories.');
			$this->redirect(array('categoryAuthor', 'id' => $model->id));
		}
	}
	public function actionRemoveCategory($id) {
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			//$this->loadModel($id, 'Category')->delete();
			$model = UserCategory::model()->findbyPk($id);
			
			// Xoa khoi db
			if ($model->delete() == 'ALL') 
			{
			
			}
			
			if (!Yii::app()->getRequest()->getIsAjaxRequest())
				$this->redirect(array('categoryAuthor'));
		} else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}
}